package com.atguigu.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
 * 自定义网关流控返回
 */
@Configuration
public class SentinelGatewayConfig {
    public SentinelGatewayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //TODO 网关限流了请求，就会调用此回调, Mono、Flux 这些是响应式编程，很厉害的一种技术(spring5新特性)，有机会学习下
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
                R error = R.error(BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getCode(),    //(10003, "请求流量多大")
                                  BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getMsg());
                String errorJson = JSON.toJSONString(error);
                //                                          Mono.just(errorJson): 发布数据，String 类型的
                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errorJson), String.class);
                return body;
            }
        });
    }
}
